package com.xyj.zjbz.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import com.xyj.zjbz.po.ZJDataSource;

/**
 * 读取XML模板。创建XML文件
 * 
 * @author 李朝衡
 * 
 */
public class XMLUtils {
	/**
	 * 读取模板文件
	 */
	private static String readXMLTemple() {
		String templPath = "dynamic/dataSourceCfgTempl.vm";//xml模板
		InputStream in = XMLUtils.class.getClassLoader()
				.getResourceAsStream(templPath);
		InputStreamReader reader = null;
		try {
			reader = new InputStreamReader(in, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(reader);
			String line = null;
			String separator = System.getProperty("line.separator");
			StringBuffer sb = new StringBuffer();
			while ((line = bufferedReader.readLine()) != null) {
				sb.append(line + separator);
			}
			bufferedReader.close();
			reader.close();
			in.close();
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
/**
 * 根据模板创建对应的datasource bean的XML文件
 * @param bz
 */
	public static void createXMLByTemp(ZJDataSource bz) {
		String cfgFile = readXMLTemple();
		cfgFile = cfgFile.replace("$DATASOURCE_NAME", bz.getBzDB())
				.replace("$URL", bz.getDbUrl())
				.replace("$USER", bz.getDbUserName())
				.replace("$PWD", bz.getDbPwd())
				.replace("$DRIVER", bz.getDbDriverClassName());
		String cfgStorePath = "dynamic";
	 	cfgStorePath = XMLUtils.class.getClassLoader().getResource(cfgStorePath).getPath();
		String path = cfgStorePath+"/"+bz.getBzDB()+".xml";
		BufferedWriter bufferedWriter =null;
		try {
			FileOutputStream outputStream = new FileOutputStream(path);
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					outputStream,"utf-8");
			 bufferedWriter = new BufferedWriter(
					outputStreamWriter);
			bufferedWriter.write(cfgFile);
			bufferedWriter.flush();
			outputStream.close();
			bufferedWriter.close();
			outputStreamWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
